package com.assess.web.util.request;


import com.alibaba.fastjson.JSONObject;
import com.assess.web.util.RespCode;
import com.assess.web.util.RespParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

/**
 * Created by guoqi.
 */
public class ResponseUtil {
    private static final Logger logger = LoggerFactory.getLogger(ResponseUtil.class);


    /**
     * 返回失败json数据
     *
     * @param response
     * @param errorCode
     */
    public static void fail(HttpServletResponse response, RespCode.EnumRespCode errorCode) {
        fail(response, errorCode, errorCode.getDesc());
    }

    /**
     * 返回失败json数据
     *
     * @param response
     * @param errorCode
     * @param errMsg
     */
    public static void fail(HttpServletResponse response, RespCode.EnumRespCode errorCode, String errMsg) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            RespParam<?> result = new RespParam<>();
            result.setCode(errorCode.getCode());
            result.setErrMsg(errMsg);
            response.getWriter().print(JSONObject.toJSONString(result));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 返回成功数据
     *
     * @param response
     * @param data
     */
    public static <T> void success(HttpServletResponse response, T data) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            RespParam<T> result = new RespParam<>();
            result.setCode(RespCode.Common.SUCCESS.getCode());
            result.setData(data);
            response.getWriter().print(JSONObject.toJSONString(result));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 返回图片
     *
     * @param response
     * @param image
     */
    public static void responseImage(HttpServletResponse response, BufferedImage image) {
        try {
            response.setContentType("image/jpeg");
            response.setDateHeader("expries", -1);
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);
            out.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
